package com.xtaller.lazy.api.tps;

import com.aliyun.oss.ClientException;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.xtaller.lazy.base.TApi;
import com.xtaller.lazy.lib.R;
import com.xtaller.lazy.lib.annotation.Token;
import com.xtaller.lazy.lib.bean.OSS;
import com.xtaller.lazy.lib.kit.OssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @version V1.0
 * @author: Taller
 * @date: 2019-04-23
 * @Description: 阿里相关api
 */
@Api(tags = "阿里相关api")
@RestController
@RequestMapping("/v1/tps")
public class AliApi extends TApi {
    @Autowired private OSS oss;

    @GetMapping("/oss")
    @ApiOperation("获取阿里OSS授权")
    @Token
    public Object getSTS(){
        String accessKeyId = oss.getAccessKeyID();
        String accessKeySecret = oss.getAccessKeySecret();
        String roleArn = oss.getRoleArn();
        long durationSeconds = oss.getTokenExpireTime();
        String policy = oss.getPolicy();
        String bucket = oss.getBucket();
        String region = oss.getRegion();

        ProtocolType protocolType = ProtocolType.HTTPS;
        Map<String, String> respMap = new LinkedHashMap<String, String>();

        try {
            final AssumeRoleResponse stsResponse =
                    OssUtil.assumeRole(region,accessKeyId,accessKeySecret, roleArn,
                            bucket,policy, protocolType, durationSeconds);

            respMap.put("AccessKeyID", stsResponse.getCredentials().getAccessKeyId());
            respMap.put("AccessKeySecret", stsResponse.getCredentials().getAccessKeySecret());
            respMap.put("SecurityToken", stsResponse.getCredentials().getSecurityToken());
            respMap.put("dir", oss.getDir());

            respMap.put("Bucket", bucket);
            respMap.put("Region", "oss-" + oss.getRegion());
            respMap.put("Endpoint",oss.getEndpoint());
            return R.ok(respMap);
        } catch (ClientException | com.aliyuncs.exceptions.ClientException e) {
            return R.error("授权失败");
        }
    }

}
